package com.asggo.g21.advice;

import com.asggo.g21.domain.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2024/3/27 11:47
 */
@RestControllerAdvice
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

  private final ObjectMapper objectMapper;

  public ResponseAdvice(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
  }

  @Override
  public boolean supports(@Nullable MethodParameter returnType,
      @Nullable Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
  }

  @Nullable
  @Override
  public Object beforeBodyWrite(Object body,
      @Nullable MethodParameter returnType,
      @Nullable MediaType selectedContentType,
      @Nullable Class<? extends HttpMessageConverter<?>> selectedConverterType,
      @Nullable ServerHttpRequest request,
      @Nullable ServerHttpResponse response) {
    if (response != null && body instanceof String) {
      response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
      try {
        return objectMapper.writeValueAsString(R.ok(body.toString()));
      } catch (JsonProcessingException e) {
        log.error("e ->{}", ExceptionUtils.getStackTrace(e));
      }
    }

    return body;
  }
}
